require('PhoenixNirvana');

const 
	fs = require('fs'),
	request = require('superagent');

module.exports = async function(self, file, target, pwd){
	let tmpl = new nirvana.Template(fs.readFileSync('./template/' + file).toString());

	let res = tmpl.render({
		target: target,
		pwd: pwd
	});	

	let [m,h,b] = nirvana.util.parseHttpPacket(res);

	let uri = m.path;
	if (!/^http/i.test(m.path)) uri = h['Host'] + uri;
	let req = request(m.method, uri)
		.set(h)
		
	if (/post/i.test(m.method))
		req.send(b);
	
	req
		.then(res => {
			if (res.ok) {
				if (res.text.trim() !== '') {
					console.log(res.text);
					if (_.find(self.namespace.flags, {flag: res.text})) console.log('已存在');
					else if (self.namespace.saveflag) {
						self.namespace.flags.push({id: uuid(), target: target, flag: res.text, time: new Date(), submitted: false});
						fs.writeFileSync('flags.json', JSON.stringify(self.namespace.flags, null, 4)); // autosave
					}
				}
			} else console.log(res.code);
		})
		.catch(err => {
			console.log(err.message);
		})
}
